import request from '@/utils/request'

export const task = {
  get: (params) => request({
    url: '/activiti/task',
    method: 'get',
    params
  }),
  getNum: (keyList) => request({
    url: '/activiti/task/number',
    method: 'get',
    params: {
      keyList: keyList && keyList.join(',')
    }
  }),
  getHistory: (params) => request({
    url: '/activiti/task/history',
    method: 'get',
    params
  })
}

export const statistics = {
  get: (params) => request({
    url: '/activiti/page',
    method: 'get',
    params
  }),
  create: (data) => request({
    url: '/activiti/page',
    method: 'post',
    data
  }),
  edit: (data) => request({
    url: '/activiti/page',
    method: 'put',
    data
  }),
  getResData: (params) => request({
    url: '/activiti/all',
    method: 'get',
    params
  })
}

export const useStatistic = async (PAGE_ID, params) => {
  const tenantId = window.localStorage.getItem('tenantId')

  try {
    // 判断是否有统计数据
    const pageData = await statistics.get({
      pageId: PAGE_ID,
      tenantId
    })

    if (pageData.length) {
      // 有则修改（应对筛选的情况）
      await statistics.edit({
        id: pageData[0].id,
        detailedJson: JSON.stringify(params)
      })
    } else {
      // 无则添加
      await statistics.create({
        pageId: PAGE_ID,
        roleId: [PAGE_ID],
        tenantId,
        detailedJson: JSON.stringify(params)
      })
    }

    // 获取最终数据
    const [res] = await statistics.getResData({
      statisticsId: PAGE_ID,
      tenantId
    })
    return JSON.parse(res.json)
  } catch (error) {
    console.log('获取数据失败', error)
  }
}
